<template>
  <div class="add-course-container">
    <h2>添加课程</h2>
    <el-form 
      ref="courseFormRef" 
      :model="courseForm" 
      :rules="rules" 
      label-width="120px"
      class="course-form"
    >
      <el-form-item label="课程名称" prop="title">
        <el-input v-model="courseForm.title" placeholder="请输入课程名称" maxlength="50" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="课程简介" prop="body">
        <el-input v-model="courseForm.body" type="textarea" placeholder="请输入课程简介" :rows="4" maxlength="200" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker 
          v-model="courseForm.startTime" 
          type="date" 
          placeholder="选择开始时间" 
          format="YYYY-MM-DD" 
          value-format="YYYY-MM-DD"
          clearable
          style="width: 100%;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker 
          v-model="courseForm.endTime" 
          type="date" 
          placeholder="选择结束时间" 
          format="YYYY-MM-DD" 
          value-format="YYYY-MM-DD"
          clearable
          style="width: 100%;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="所属类别" prop="categoryid">
        <el-select v-model="courseForm.categoryid" placeholder="请选择课程类别" clearable>
          <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上课老师" prop="teachername">
        <el-input v-model="courseForm.teachername" placeholder="请输入上课老师姓名" maxlength="20" show-word-limit></el-input>
      </el-form-item>
      
      <!-- 图片设置方式选择 -->
      <el-form-item label="图片设置方式">
        <el-radio-group v-model="imageSettingType">
          <el-radio label="url">使用图片链接</el-radio>
          <el-radio label="upload">上传图片</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <!-- 图片链接输入 -->
      <el-form-item 
        label="图片链接" 
        prop="picPaths" 
        v-if="imageSettingType === 'url'"
        key="url-input"
      >
        <el-input 
          v-model="courseForm.picPaths" 
          placeholder="请输入课程图片URL链接" 
          maxlength="500"
          show-word-limit
        >
          <template #append>
            <el-button @click="previewImage" :disabled="!courseForm.picPaths">预览</el-button>
          </template>
        </el-input>
        <div class="image-preview" v-if="courseForm.picPaths && showPreview">
          <p>图片预览：</p>
          <img :src="courseForm.picPaths" alt="课程图片预览" @error="handlePreviewError" />
        </div>
      </el-form-item>
      
      <!-- 图片上传 -->
      <el-form-item 
        label="课程照片" 
        prop="picPaths" 
        v-if="imageSettingType === 'upload'"
        key="upload-input"
      >
        <el-upload 
          v-model:file-list="fileList" 
          action="" 
          :auto-upload="false" 
          :on-change="handleFileChange"
          :show-file-list="true"
          :before-upload="beforeUpload"
          accept="image/*"
          :limit="1"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，单个文件不超过500kb
            </div>
          </template>
        </el-upload>
        <div class="image-preview" v-if="uploadedImageUrl">
          <p>图片预览：</p>
          <img :src="uploadedImageUrl" alt="上传图片预览" />
        </div>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="图片预览" width="50%">
      <div style="text-align: center;">
        <img :src="courseForm.picPaths" alt="课程图片" style="max-width: 100%; max-height: 400px;" />
      </div>
      <template #footer>
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { api } from '../api'
import { ElMessage } from 'element-plus'

export default {
  name: 'AddCourse',
  setup() {
    const userStore = useUserStore()
    const courseForm = reactive({
      title: '',
      body: '',
      startTime: '',
      endTime: '',
      categoryid: null,
      picPaths: '',
      teachername: ''
    })
    
    const fileList = ref([])
    const categories = ref([])
    const courseFormRef = ref(null)
    const imageSettingType = ref('url') // 默认使用链接方式
    const showPreview = ref(false)
    const previewDialogVisible = ref(false)
    const uploadedImageUrl = ref('')
    
    const rules = {
      title: [
        { required: true, message: '请输入课程名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      body: [
        { required: true, message: '请输入课程简介', trigger: 'blur' },
        { min: 10, max: 200, message: '长度在 10 到 200 个字符', trigger: 'blur' }
      ],
      startTime: [
        { required: true, message: '请选择开始日期', trigger: 'change' }
      ],
      endTime: [
        { required: true, message: '请选择结束日期', trigger: 'change' }
      ],
      categoryid: [
        { required: false, message: '请选择课程类别', trigger: 'change' }
      ],
      teachername: [
        { required: true, message: '请输入上课老师姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      picPaths: [
        { 
          validator: (rule, value, callback) => {
            if (imageSettingType.value === 'url' && !value) {
              callback(new Error('请输入图片链接'));
            } else {
              callback();
            }
          }, 
          trigger: 'blur' 
        }
      ]
    }
    
    // 获取课程类别列表
    const fetchCategories = async () => {
      try {
        console.log('准备获取课程类别...');
        // 使用现有的API方法获取类别数据
        const response = await api.items.getAll(5);
        
        // 如果返回的数据是空数组或无效，则设置为null
        if (Array.isArray(response) && response.length > 0) {
          categories.value = response;
        } else {
          categories.value = [];
          courseForm.categoryid = null;
        }
        
        console.log('获取课程类别成功:', categories.value);
      } catch (error) {
        console.error('获取课程类别失败:', error);
        categories.value = [];
        courseForm.categoryid = null;
      }
    };
    
    // 文件上传前的校验
    const beforeUpload = (file) => {
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;
      
      if (!isJPGOrPNG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!');
        return false;
      }
      if (!isLt500K) {
        ElMessage.error('上传图片大小不能超过 500KB!');
        return false;
      }
      return true;
    };
    
    // 处理文件变化
    const handleFileChange = (file, files) => {
      fileList.value = files;
      
      if (file.status === 'ready') {
        // 创建本地URL用于预览
        const reader = new FileReader();
        reader.onload = (e) => {
          uploadedImageUrl.value = e.target.result;
          // 对于实际项目，这里应该上传到服务器并获取服务器返回的URL
          // 这里我们使用本地URL作为示例
          courseForm.picPaths = uploadedImageUrl.value;
        };
        reader.readAsDataURL(file.raw);
      }
    };
    
    // 预览图片
    const previewImage = () => {
      if (courseForm.picPaths) {
        previewDialogVisible.value = true;
      } else {
        ElMessage.warning('请输入图片链接');
      }
    };
    
    // 处理预览图片加载错误
    const handlePreviewError = () => {
      ElMessage.error('图片加载失败，请检查链接是否正确');
      showPreview.value = false;
    };
    
    // 提交表单
    const submitForm = async () => {
      try {
        // 检查用户是否已登录
        if (!userStore.isAuthenticated) {
          ElMessage.error('请先登录后再添加课程');
          return;
        }
        
        await courseFormRef.value.validate();
        
        // 准备提交的数据 - 确保字段与后端表结构匹配
        const submitData = {
          title: courseForm.title,
          body: courseForm.body,
          userid: userStore.userInfo?.id,
          picPaths: courseForm.picPaths || '',
          teachername: courseForm.teachername,
          startTime: courseForm.startTime, // 直接使用YYYY-MM-DD格式
          endTime: courseForm.endTime,     // 直接使用YYYY-MM-DD格式
          categoryid: courseForm.categoryid || null
        };
        
        console.log('准备提交的课程数据:', submitData);
        console.log('表索引: 6 (courses表)');
        
        // 修复：正确调用API，传递typeIndex=6对应courses表
        const response = await api.items.add(submitData, 6);
        
        console.log('提交响应:', response);
        
        if (response && response.success !== false) {
          ElMessage.success('课程添加成功！');
          resetForm();
        } else {
          ElMessage.error(response?.message || '课程添加失败，请重试！');
        }
      } catch (error) {
        console.error('提交表单时出错:', error);
        // 更详细的错误信息
        if (error.response) {
          ElMessage.error(`提交失败: ${error.response.data?.message || error.response.statusText}`);
        } else if (error.message) {
          ElMessage.error(`提交失败: ${error.message}`);
        } else {
          ElMessage.error('提交失败，请检查网络连接！');
        }
      }
    };
    
    // 重置表单
    const resetForm = () => {
      const form = courseFormRef.value
      if (form) {
        form.resetFields()
      }
      fileList.value = [];
      uploadedImageUrl.value = '';
      showPreview.value = false;
      previewDialogVisible.value = false;
    }
    
    // 监听图片链接变化
    const watchPicPaths = () => {
      if (courseForm.picPaths && imageSettingType.value === 'url') {
        showPreview.value = true;
      } else {
        showPreview.value = false;
      }
    };
    
    // 组件挂载时获取类别列表
    onMounted(() => {
      fetchCategories();
    })
    
    return {
      courseForm,
      rules,
      categories,
      fileList,
      courseFormRef,
      imageSettingType,
      showPreview,
      previewDialogVisible,
      uploadedImageUrl,
      submitForm,
      resetForm,
      fetchCategories,
      beforeUpload,
      handleFileChange,
      previewImage,
      handlePreviewError,
      watchPicPaths
    }
  }
}
</script>

<style scoped>
.add-course-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 2rem;
}

.add-course-container h2 {
  font-size: 1.8rem;
  color: #333;
  margin-bottom: 1.5rem;
  text-align: center;
  padding-bottom: 1rem;
  border-bottom: 2px solid #42b983;
}

.course-form {
  margin-top: 1rem;
}

.el-form-item {
  margin-bottom: 1.5rem;
}

/* 图片预览样式 */
.image-preview {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.image-preview p {
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.image-preview img {
  max-width: 100%;
  max-height: 200px;
  border-radius: 4px;
}

/* 修复文字输入显示问题 */
.el-form-item__content {
  line-height: 1.8;
}

/* 确保输入框内文字可见 - 全局样式增强 */
:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  line-height: 1.8 !important;
  color: #000000 !important; /* 使用纯黑色提高对比度 */
  background-color: #ffffff !important;
  border-color: #dcdfe6 !important;
  padding: 12px !important;
  font-size: 14px !important;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif !important;
  opacity: 1 !important;
  caret-color: transparent !important; /* 去掉光标选中时的蓝色竖线 */
}

/* 确保输入框焦点状态的可见性 */
:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus) {
  color: #000000 !important; /* 使用纯黑色提高对比度 */
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
  background-color: #ffffff !important;
  caret-color: transparent !important; /* 去掉光标选中时的蓝色竖线 */
}

/* 增强输入框在输入时文字可见性 - 针对各种状态的覆盖样式 */
:deep(.el-input__wrapper),
:deep(.el-textarea__wrapper) {
  background-color: #ffffff !important;
}

:deep(.el-input.is-focus .el-input__inner),
:deep(.el-textarea.is-focus .el-textarea__inner) {
  color: #000000 !important; /* 使用纯黑色提高对比度 */
  background-color: #ffffff !important;
  caret-color: transparent !important; /* 去掉光标选中时的蓝色竖线 */
}

:deep(.el-input__inner::placeholder),
:deep(.el-textarea__inner::placeholder) {
  color: #909399 !important;
  opacity: 1 !important;
}

/* 确保placeholder文字可见 */
.el-input__inner::placeholder,
.el-textarea__inner::placeholder {
  color: #909399;
  opacity: 1;
}

/* 确保下拉框内文字可见 */
.el-select .el-input__inner {
  color: #303133;
  font-size: 14px;
}

/* 确保选项文字可见 */
.el-select-dropdown__item {
  color: #303133;
  font-size: 14px;
  line-height: 1.8;
  padding: 10px 20px;
}

.el-button {
  min-width: 80px;
}

.el-button + .el-button {
  margin-left: 10px;
}

/* 单选按钮组样式 */
:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.el-radio) {
  margin-right: 0;
}

@media (max-width: 768px) {
  .add-course-container {
    padding: 1.5rem;
    margin: 1rem;
  }
  
  .add-course-container h2 {
    font-size: 1.5rem;
  }
  
  .el-form-item__label {
    width: 100px;
  }
  
  :deep(.el-radio-group) {
    flex-direction: column;
    gap: 10px;
  }
}
</style>